﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Service4u2.Common;
using System.Xml.Linq;

namespace MoAds.AdAdapters.MillennialMedia
{
    public class MillennialMediaService
    {
        private readonly String uri = "http://ads.mp.mydas.mobi/getAd";

        /// <summary>
        /// Occurs when a result is received.
        /// </summary>
        public event EventHandler<EventArgs<MillennialMediaResponse>> ResultEvent;

        /// <summary>
        /// Occurs when an exception occurs..
        /// </summary>
        public event EventHandler<EventArgs<Exception>> ExceptionEvent;

        public void BeginAdsAsync(MillennialMediaRequest request)
        {
            //  Creating Web client object 
            WebClient zestadzClient = new WebClient();

            zestadzClient.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(mmClient_DownloadStringCompleted);

            UriBuilder ub = new UriBuilder(uri);
            ub.Query = request.GetQueryString();

            zestadzClient.DownloadStringAsync(ub.Uri);
            
        }

        private void mmClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {

            // if error, return
            if (e.Error != null)
            {
                if (ExceptionEvent != null) ExceptionEvent(this, new EventArgs<Exception>() { Argument = e.Error });
                return;
            }

            XElement xmlad = XElement.Parse(e.Result);

            MillennialMediaResponse response = null;

            if (xmlad.Descendants("img") != null)
            {
                try
                {
                    response = new MillennialMediaResponse();

                    response.ClickUri = xmlad.Attribute("href").Value;
                    response.ImageUri = xmlad.Element("img").Attribute("src").Value;

                    if (ResultEvent != null) ResultEvent(this, new EventArgs<MillennialMediaResponse>() { Argument = response });
                }
                catch (Exception ex)
                {
                    if (ExceptionEvent != null) ExceptionEvent(this, new EventArgs<Exception>() { Argument = ex });
                }
            }
        }
    }
}
